package com.yunzhong.appointment.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;


public class FileUtilss {



    /**
     * 文件上传到硬盘的目录
     */
    @Value("${uploadToDiskPath}")
    private static String FILEUPLOADDISKPATH = "";


    /**
     * 上传文件到硬盘
     * @param picFile 上传的文件
     * @return 文件名
     */
    public static String uploadToDisk(MultipartFile picFile) {
        File dirFile = new File(FILEUPLOADDISKPATH);
        //判断目录是否存在,如果不存在,则创建
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        return saveFile(picFile, FILEUPLOADDISKPATH);
    }

    /**
     * 从硬盘删除文件
     * @param fileName 文件名
     * @return true删除成功, false删除失败
     */
    public boolean deleteFileFromDisk(String fileName) {
        boolean bj = false;
        //如果文件名为null或者为空,则不删除
        if (fileName != null && !"".equals(fileName)) {
            File file = new File(FILEUPLOADDISKPATH+"/"+fileName);
            if (file.exists()) {
                bj = file.delete();
            }
        }
        return bj;
    }

    /**
     * 从硬盘中下载文件
     */
    public void downloadFromDisk(String fileName, HttpServletResponse response) throws IOException {
        if (StringUtils.isNotEmpty(fileName)) {
            File file = new File(FILEUPLOADDISKPATH+"/"+fileName);
            if (!file.exists()) {
                response.setContentType("text/html; charset=UTF-8");
                response.getWriter().print("<html><body>您要下载的资源已被删除！<a href='javascript:history.back()'>返回</a></body></html>");
                response.getWriter().close();
                return;
            }else {
                /*开始下载*/
                response.setContentType("multipart/form-data");
                // 设置文件名
                response.addHeader("Content-Disposition","attachment;fileName=" + fileName );
                byte[] buffer = new byte[4096];
                FileInputStream fis  = null;
                try{
                    fis  = new FileInputStream(file);
                    OutputStream os = response.getOutputStream();
                    int i = fis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = fis.read(buffer);
                    }
                    fis.close();
                    os.flush();
                    os.close();
                }catch(Exception  e){
                    e.printStackTrace();
                }
            }
        }else {
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().print("<html><body>您要下载的资源不存在！<a href='javascript:history.back()'>返回</a></body></html>");
            response.getWriter().close();
        }
    }

    /**
     * 存储到指定的目录内
     * @param picFile 上传的文件
     * @param path 文件路径
     * @return 文件名
     */
    private static String saveFile(MultipartFile picFile, String path) {
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        //获取文件的扩展名
        String picFileName = picFile.getOriginalFilename();
        String ext = picFileName.substring(picFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+ext;
        File dest = new File(path+fileName);
        try {
            picFile.transferTo(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }
}
